const { apiGetVenueInfoById } = require("@/api/venue");

// components/showReservation/index.js
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    reservation: {
      type: Array,
      value: []
    },
    hasMore: {
      type: Boolean,
      value: false
    }
  },

  data: {
    groupedReservations: [],
    processedIds: [], // 用于跟踪已处理的预约ID
    // hasMore: false
  },
  
  observers: {
    'reservation': async function(reservations) {
      if (!reservations || reservations.length === 0) return;
      
      // 过滤出尚未处理的新预约
      const newReservations = reservations.filter(res => !this.data.processedIds.includes(res.id));
      if (newReservations.length === 0) return;
      
      // 处理新的预约数据
      await this.processReservations(newReservations);
    }
  },

  methods: {
    async processReservations(reservations) {
      // 复制当前分组数据
      const grouped = {};
      
      // 将现有分组数据转换回对象格式
      this.data.groupedReservations.forEach(group => {
        grouped[this.parseDate(group.date)] = group.items;
      });
      
      // 处理新的预约数据
      const newProcessedIds = [...this.data.processedIds];
      
      for (const res of reservations) {
        const date = res.start_time.split('T')[0];
        if (!grouped[date]) {
          grouped[date] = [];
        }
        
        const formattedItem = await this.formatItem(res);
        grouped[date].push(formattedItem);
        
        // 记录已处理的ID
        newProcessedIds.push(res.id);
      }
      
      // 转换为数组格式
      const result = Object.keys(grouped).map(date => ({
        date: this.formatDate(date),
        items: grouped[date]
      }));
      
      this.setData({ 
        groupedReservations: result,
        processedIds: newProcessedIds
      });
    },
    
    formatDate(dateStr) {
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
      const weekDay = weekDays[date.getDay()];
      
      return `${year}年${month}月${day}日 星期${weekDay}`;
    },
    
    parseDate(formattedDate) {
      // 从格式化的日期字符串中提取原始日期
      // 例如："2023年5月1日 星期一" -> "2023-05-01"
      const matches = formattedDate.match(/(\d+)年(\d+)月(\d+)日/);
      if (matches) {
        const year = matches[1];
        const month = matches[2].padStart(2, '0');
        const day = matches[3].padStart(2, '0');
        return `${year}-${month}-${day}`;
      }
      return "";
    },
    
    async formatItem(item) {
      const venueInfo = await this.getVenueInfoById(item.venue_id);
      const {name, number} = venueInfo;
      
      const start = item.start_time.split('T')[1].substring(0, 5);
      const end = item.end_time.split('T')[1].substring(0, 5);
      
      return {
        id: item.id, // 保存预约ID用于取消操作
        venue: `${name}-第${number}号场`,
        time: `${start}-${end}`,
        status: item.status,  // 新增状态字段
        showCancel: item.status === 2  // 添加是否显示取消按钮的标识
      };
    },
    
    async getVenueInfoById(id) {
      const res = await apiGetVenueInfoById(id);
      return res.data;
    },
    
    // 取消预约
    cancelReservation(e) {
      const id = e.currentTarget.dataset.id;
      wx.showModal({
        title: '提示',
        content: '确定要取消此预约吗？',
        success: (res) => {
          if (res.confirm) {
            // 触发取消预约事件，由父页面处理
            this.triggerEvent('cancelReservation', { id });
          }
        }
      });
    }
  }
})